package com.iqilu.ksd.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.constant.NewsType;
import com.iqilu.ksd.event.PayEvent;
import com.iqilu.ksd.utils.BaseUtils;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.ShareUtils;
import com.jude.swipbackhelper.SwipeBackHelper;

import java.io.File;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 广告展示页面
 * <p>
 * Created by coofee on 2015/11/12.
 */
public class ADActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private static String TAG = "AdActivity";

    private String adUrl;
    private String shareUrl;
    private String title;
    private String description;
    private String shareicon;
    private String thumb;
    private String type;
    private String orderId;
    private String uniqueid;

    private Boolean fromStart = false;
    private Boolean fromJPush = false;
    private Boolean fromScan = false;
    private Boolean showShareBtn = true;
    private MyApplication application;

    ValueCallback<Uri> mUploadMessage;
    ValueCallback<Uri[]> mUploadMessagesAboveL;
    private Uri cameraUri;

    private static final int REQUEST_CODE_LOGIN = 1;
    private static final int REQUEST_CODE_WXPAY = 2;
    private static final int REQUEST_CODE_FILECHOOSER = 3;
    private static final int REQUEST_CODE_CAMERA = 4;

    private static final int PER_STORAGE = 101;

    private RelativeLayout layRoot;
    private WebView wvContent;
    private ImageView btBack;
    private ImageView btShare;
    private ImageView btLove;
    private LinearLayout layComment;
    private LinearLayout layLike;
    private ProgressBar pbBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ad);
        ShareSDK.initSDK(this);
        application = (MyApplication) getApplication();
        initView();
        Intent intent = getIntent();
        fromStart = intent.getBooleanExtra("fromStart", false);
        fromJPush = intent.getBooleanExtra("fromJPush", false);
        fromScan = intent.getBooleanExtra("fromScan", false);
        showShareBtn = intent.getBooleanExtra("showShareBtn",true);
        adUrl = intent.getStringExtra("adUrl");
        shareUrl = adUrl;
        title = intent.getStringExtra("title");
        description = getString(R.string.description);
        shareicon = intent.getStringExtra("shareicon");
        thumb = intent.getStringExtra("thumb");
        type = intent.getStringExtra("type");
        if ((fromScan) || adUrl.contains("iuser.iqilu.com")) {
            btShare.setVisibility(View.INVISIBLE);
        }
        if (fromStart) {
            SwipeBackHelper.getCurrentPage(this).setSwipeBackEnable(false);
        }
        if(!showShareBtn){
            btShare.setVisibility(View.GONE);
        }
        btBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
        uniqueid = BaseUtils.getUniqueid(this);
        init(false);
    }

    private void initView() {
        layRoot = getView(R.id.lay_root);
        wvContent = getView(R.id.wv_content);
        btBack = getView(R.id.bt_back);
        btLove = getView(R.id.bt_love);
        btShare = getView(R.id.bt_share);
        layComment = getView(R.id.lay_comment);
        layLike = getView(R.id.lay_like);
        pbBar = getView(R.id.pb_bar);
        btShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                share();
            }
        });
        // 隐藏底部按钮
        btBack.setImageResource(R.drawable.bt_close);
        btLove.setVisibility(View.INVISIBLE);
        layComment.setVisibility(View.INVISIBLE);
        layLike.setVisibility(View.INVISIBLE);
    }

    private void init(boolean paySuccess) {
        String[] perms = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, getString(R.string.per_con_storage), PER_STORAGE, perms);
            return;
        }
        if (!TextUtils.isEmpty(adUrl)) {
            if (paySuccess) {
                adUrl = shareUrl + "pay/" + orderId + "?pay=success";
            } else {
                adUrl = getEncryptStr(adUrl);
            }
            Log.i(TAG, "adUrl=" + adUrl);
            WebSettings settings = wvContent.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setSupportZoom(false);
            settings.setDisplayZoomControls(false);
            settings.setUseWideViewPort(true);
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            settings.setLoadWithOverviewMode(true);
            settings.setDomStorageEnabled(true);
            settings.setDatabaseEnabled(true);
            String ua = settings.getUserAgentString();
            settings.setUserAgentString(ua + ";shandian/android");
            wvContent.addJavascriptInterface(new JsObject(this), "clicklistener");
            wvContent.setWebChromeClient(new MyWebChromeClient());
            wvContent.setWebViewClient(new MyWebViewClient(adUrl));
            wvContent.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (event.getAction() == KeyEvent.ACTION_DOWN) {
                        if (keyCode == KeyEvent.KEYCODE_BACK && wvContent.canGoBack()) {
                            wvContent.goBack();   //后退
                            //webview.goForward();//前进
                            return true;    //已处理
                        }
                    }
                    return false;
                }
            });
            if(adUrl.contains("?")){
                adUrl += "&uniqueid="+uniqueid;
            }else {
                adUrl += "?uniqueid="+uniqueid;
            }
            wvContent.loadUrl(adUrl);
        } else {
            Toast.makeText(this, R.string.content_ad_null, Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private class MyWebViewClient extends WebViewClient {

        private String url;

        public MyWebViewClient(String url) {
            this.url = url;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            pbBar.setVisibility(View.GONE);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            pbBar.setVisibility(View.GONE);
        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress != 100) {
                pbBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            Log.d(TAG, "openFileChooser");
            if (mUploadMessage != null) return;
            mUploadMessage = uploadMsg;
//            chosePicture();
            selectImage();
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // For Android  > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

        // For Android 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

            if (mUploadMessagesAboveL != null) {
                mUploadMessagesAboveL.onReceiveValue(null);
            } else {
                mUploadMessagesAboveL = filePathCallback;
//                chosePicture();
                selectImage();
            }
            return true;
        }

    }

    public class JsObject {

        private Context context;

        public JsObject(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void goToLogin() {
            startActivityForResult(new Intent(context, LoginActivity.class), REQUEST_CODE_LOGIN);
        }

        @JavascriptInterface
        public void wxPay(String orderId) {
            ADActivity.this.orderId = orderId;
            Intent intent = new Intent(context, PayActivity.class);
            intent.putExtra("payType", "weixin");
            intent.putExtra("orderId", orderId);
//            startActivityForResult(intent, REQUEST_CODE_WXPAY);
            startActivity(intent);
        }

        @JavascriptInterface
        public void zfbPay() {

        }

    }

    private void selectImage() {
        if (Build.VERSION.SDK_INT < 21) { //5.0以下的系统
            openCarcme();
            return;
        }
        String[] selectPicTypeStr = {getString(R.string.user_from_photo), getString(R.string.user_from_album)};
        new AlertDialog.Builder(this)
                .setOnCancelListener(new ReOnCancelListener())
                .setItems(selectPicTypeStr,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    // 相机拍摄
                                    case 0:
                                        openCarcme();
                                        break;
                                    // 手机相册
                                    case 1:
                                        chosePicture();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }).show();
    }

    /**
     * 本地相册选择图片
     */
    private void chosePicture() {
        Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        innerIntent.setType("image/*");
        Intent wrapperIntent = Intent.createChooser(innerIntent, null);
        startActivityForResult(wrapperIntent, REQUEST_CODE_FILECHOOSER);
    }

    /**
     * 打开照相机
     */
    private void openCarcme() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        String imagePaths = Environment.getExternalStorageDirectory().getPath() + "/BigMoney/Images/" + (System.currentTimeMillis() + ".jpg");
        String imagePaths = CacheUtils.getCacheDir(this) + (System.currentTimeMillis() + ".jpg");
        // 必须确保文件夹路径存在，否则拍照后无法完成回调
        File vFile = new File(imagePaths);
        if (!vFile.exists()) {
            File vDirPath = vFile.getParentFile();
            vDirPath.mkdirs();
        } else {
            if (vFile.exists()) {
                vFile.delete();
            }
        }
        cameraUri = Uri.fromFile(vFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }

    /**
     * 选择照片后结束
     *
     * @param data
     */
    private Uri afterChosePic(Intent data) {
        if (data != null) {
            final String path = data.getData().getPath();
            if (path != null && (path.endsWith(".png") || path.endsWith(".PNG") || path.endsWith(".jpg") || path.endsWith(".JPG") || path.endsWith(".jpeg") || path.endsWith(".JPEG"))) {
                Log.i(TAG, "path=" + path);
                return data.getData();
            } else {
                Toast.makeText(this, R.string.pic_format_error, Toast.LENGTH_SHORT).show();
            }
        }
        return null;
    }

    /**
     * dialog监听类
     */
    private class ReOnCancelListener implements DialogInterface.OnCancelListener {
        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }

            if (mUploadMessagesAboveL != null) {
                mUploadMessagesAboveL.onReceiveValue(null);
                mUploadMessagesAboveL = null;
            }
        }
    }

    private void share() {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(title);
        sp.setTitleUrl(shareUrl); // 标题的超链接
        sp.setText(description);
        sp.setSiteUrl(shareUrl);
        sp.setUrl(shareUrl);
        //url类型分享图用 thumb   ad类型分享使用 shareicon
        if (NewsType.AD.equals(type)) {
            sp.setImageUrl(shareicon);
        } else {
            sp.setImageUrl(thumb);
        }
        sp.setSite(getString(R.string.app_name));
        ShareUtils.getInstance().setShareParams(this, sp).show();
    }

    private void back() {
        if (fromStart || (fromJPush && !application.getMainStarted())) {
            startActivity(new Intent(this, MainActivity.class));
        }
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_LOGIN:
                    Log.i(TAG, "REQUEST_CODE_LOGIN...");
                    adUrl = shareUrl;
                    init(false);
                    break;
                case REQUEST_CODE_WXPAY:
//                    init(true);
                    break;
                case REQUEST_CODE_FILECHOOSER:
                    if (mUploadMessagesAboveL != null) {
                        onActivityResultAboveL(requestCode, resultCode, data);
                    }
                    if (mUploadMessage == null) return;
                    Uri uri = null;
                    if (requestCode == REQUEST_CODE_FILECHOOSER && resultCode == RESULT_OK) {
                        uri = afterChosePic(data);
                    }
                    mUploadMessage.onReceiveValue(uri);
                    mUploadMessage = null;
                    break;
                case REQUEST_CODE_CAMERA:
                    if (mUploadMessagesAboveL != null) {
                        onActivityResultAboveL(requestCode, resultCode, data);
                    }
                    if (mUploadMessage == null) return;
                    Uri uri2 = null;
                    if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
                        uri2 = cameraUri;
                    }
                    mUploadMessage.onReceiveValue(uri2);
                    mUploadMessage = null;
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        init(false);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.per_con_storage))
                    .setTitle(getString(R.string.per_title))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setRequestCode(PER_STORAGE)
                    .build()
                    .show();
        }
    }

    /**
     * 5.0以后机型 返回文件选择
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {

        Uri[] results = null;

        if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
            results = new Uri[]{cameraUri};
        }

        if (requestCode == REQUEST_CODE_FILECHOOSER && resultCode == RESULT_OK) {
            if (data != null) {
                String dataString = data.getDataString();
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }

        mUploadMessagesAboveL.onReceiveValue(results);
        mUploadMessagesAboveL = null;
        return;
    }

    public void onEventMainThread(PayEvent event) {
        Log.i(TAG, "PayEvent...");
        init(event.isPaySuccess());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        layRoot.removeView(wvContent);
        wvContent.destroy();
    }
}
